package com.gzhryc.shared_device.iot.core;

import com.gzhryc.common.logging.Logger;

import java.util.concurrent.*;

/**
 * 网络设备工作线程池
 */
public class NetworkDeviceWorkThreadPool {

    static Logger log = Logger.getLogger(NetworkDeviceWorkThreadPool.class);

    static NetworkDeviceWorkThreadPool me;

    public static NetworkDeviceWorkThreadPool self() {
        if(me == null) {
            me = new NetworkDeviceWorkThreadPool();
        }
        return me;
    }

    ThreadPoolExecutor executorService;

    public void initial() {
        if(executorService != null) {
            executorService.shutdown();
            executorService = null;
        }
        int poolSize = Runtime.getRuntime().availableProcessors();
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1024);
        RejectedExecutionHandler policy = new ThreadPoolExecutor.AbortPolicy();
        //可堵塞的线程池队列
        executorService = new ThreadPoolExecutor(poolSize, poolSize * 2, 180, TimeUnit.SECONDS,queue,policy);
    }


    public boolean execute(Runnable runnable) {
        if (executorService != null) {
            try {
                executorService.execute(runnable);
                return true;
            } catch (Exception e) {
                log.error("网络设备工作线程池添加新任务失败，丢失任务", e);
            }
        } else {
            log.error("网络设备工作线程池未初始化");
        }
        return false;
    }

}
